var Users = {

    selected_row_id : null,

    /* dataTable Object */
    objGrid: null,

    /* Function init
     * @param void
     * @return void
     * @access public
     * */
    init:function(){
        var self = this;

        /*Sortable Table */
        var dataUrl = $('#table-url').val();

        self.objGrid = $('#flex').flexigrid({
            url: dataUrl,
            dataType: 'json',
            colModel : [
                {display: 'ID', name : 'id', width : 20, sortable : false, align: 'left', hide:true},
                {display: 'User Name', name : 'username', width : 140, sortable : true, align: 'center', hide:false},
                {display: 'First Name', name : 'first_name', width : 140, sortable : true, align: 'center', hide:false},
                {display: 'Last Name', name : 'last_name', width : 140, sortable : true, align: 'center', hide:false},
                {display: 'Group', name : 'group_id', width : 140, sortable : true, align: 'center', hide:false},
                {display: 'Status', name : 'active', width : 140, sortable : false, align: 'center', hide:false}
            ],
            formFields : [
                {type:'buttom',name: 'Add', bclass: 'add', onpress : self.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Edit', bclass: 'edit', onpress : self.handleGridEvent},
                {separator: true},
                {type:'buttom',name: 'Delete', bclass: 'delete', onpress : self.handleGridEvent}
            ],
            searchitems : [
                {display: 'User Name', name : 'username', isdefault: true},
                {display: 'First Name', name : 'first_name'},
                {display: 'Last Name', name : 'last_name'}
            ],
            checkboxSelection: true,
            columnControl:false,
            sortname: "id",
            sortorder: "desc",
            usepager: true,
            /*title: 'Users',*/
            useRp: false,
            rp: 15,
            showTableToggleBtn: false,
            width: 813,
            height: 200
        });

        $('#user-save-btn').click(function(){
            self.saveUser();
        });

        $('#user-cancel-btn').click(function(){
            document.getElementById('user-form').reset();
            $.validationEngine.closePrompt('.formError',true);
            $.colorbox.close();
            self.selected_row_id = null;
        });

        jLib.afterClosePopUpForm('user-form',function(){
            self.selected_row_id = null;
            document.getElementById('user-form').reset();
        });

       // $("#user-form").validationEngine();

        $("#mekgrid1 table").thfloat({
            attachment : "#mekgrid1 .tdDiv"
        });
    },

    handleGridEvent: function(com, grid){
        if (com == 'Add') {
            $.colorbox({
                inline:true,
                scrolling:false,
                overlayClose:false,
                escKey:false,
                title:'User Information',
                href:"#user-form-window"
            });
        }
        else if (com == 'Edit') {
            if(jLib.rowSelectedCheck(grid,1)){
                Users.editUser(jLib.getSelectedRowIds(grid));
            }
        }
        else if (com == 'Delete') {
            if(jLib.rowSelectedCheck(grid)){
                Users.deleteUser(grid);
            }
        }
    },

    editUser:function(row_ids){
        var self = this;

        var userID = row_ids[0];
        var url = $('#load-user-url').val();
        var query = 'type=load&user-id=' + userID;
        $.post(url, query, function(response){
            if(response.code === 0){
                var dataUser = response.data.User;

                $('#user-form-window #user-form #first_name').val(dataUser.first_name);
                $('#user-form-window #user-form #last_name').val(dataUser.last_name);
                $('#user-form-window #user-form #username').val(dataUser.username);
                $('#user-form-window #user-form #group_id').val(dataUser.group_id);
                $('#user-form-window #user-form #active').val(dataUser.active);

                self.selected_row_id = userID;

                $.colorbox({
                    inline:true,
                    scrolling:false,
                    overlayClose:false,
                    escKey:false,
                    title:'User Information',
                    href:"#user-form-window"
                });
            }
            /* When there are Errors */
            else if(response.code === 1){
                /* Alert the user that the server response*/
                jLib.setFeedback(response.mesg, 'error_message', false);
            }
        },'json');
    },

    saveUser:function(){
        var self = this;
        /* Validate the form*/
        var validationStatus =  $('#user-form').validationEngine({returnIsValid:true});
        /* When the Validation Status is true meaning that the data input are correct then the data can be processed. */
        if(validationStatus){

            var query = 'model=User&row_id='+self.selected_row_id+'&'+ $('#user-form').serialize();
            var url = $("#table-url").val();
            /* Send the data to the server and handle the server response */
            $.post(url, query, function(response){
                var txt = '';
                if(typeof response.mesg  == 'object'){
                    for(megTxt in response.mesg){
                        txt += response.mesg[megTxt]+'<br />';
                    }
                }
                else{
                    txt = response.mesg
                }

                if(response.code === 0){
                    /* Alert the user that the server response*/
                    jLib.setFeedback(txt, 'success_message', false);

                    if(self.selected_row_id){
                        // Chnge the cell data
                        update_data = {
                            'first_name': $('#user-form-window #user-form #first_name').val(),
                            'last_name': $('#user-form-window #user-form #last_name').val(),
                            'username': $('#user-form-window #user-form #username').val(),
                            'group_id': $('#user-form-window #user-form #group_id option:selected').text(),
                            'active': $('#user-form-window #user-form #active').val() == 'y' ? 'Active' : 'Inactive'
                        };
                        jLib.updateGridData(self.objGrid, update_data);
                        //
                        jLib.highlightRow(self.objGrid);
                    }
                    else{
                        $(self.objGrid).flexReload();
                    }
                    document.getElementById('user-form').reset();
                    $.validationEngine.closePrompt('.formError',true)
                    $.colorbox.close();
                    self.selected_row_id = null;

                }
                /* When there are Errors */
                else if(response.code === 1){
                    /* Alert the user that the server response*/
                    jLib.setFeedback(txt, 'error_message', false);
                }
            },'json');
        }
    },


    deleteUser:function(grid){
        var url = $('#delete-url').val();
        jLib.do_delete(url,grid);
    }

};

/* when the page is loaded */
$(document).ready(function() {
    Users.init();
});